package by.grsu.gordienko.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;




import by.grsu.gordienko.entity.Service;
import by.grsu.gordienko.table.ServiceTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class ServiceDao extends AbstractDao<ServiceTable, Service> {

	public ServiceDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	public List<Service> searchByName(String name) {
		final ServiceTable serviceTable = deserializeFromXml();
		List<Service> listService = new ArrayList<Service>();
		for (Service b : serviceTable.getRows()) {
			if (b.getName().equals(name)) {
				listService.add(b);
			}
		}
		return listService;
	}

	
	public List<Service> searchByDate(Date d) {
		final ServiceTable serviceTable = deserializeFromXml();
		List<Service> listService = new ArrayList<Service>();
		for (Service b : serviceTable.getRows()) {
			if (b.getDate().equals(d)) {
				listService.add(b);
			}
		}
		return listService;
	}

	public void saveNew(Service newService) {
		newService.setId(getNextId());
		final ServiceTable serviceTable = deserializeFromXml();
		serviceTable.getRows().add(newService);
		serializeToXml(serviceTable);

	}

	@Override
	public void update(Service entity) {
		final ServiceTable serviceTable = deserializeFromXml();
		for (Service b : serviceTable.getRows()) {
			if (b.getId().equals(entity.getId())) {
				
				b.setCatalogid(entity.getCatalogid());
				b.setDate(entity.getDate());
				b.setName(entity.getName());
			}
		}
		serializeToXml(serviceTable);
	}

	@Override
	public Service get(Serializable id) {
		final ServiceTable serviceTable = deserializeFromXml();
		for (Service b : serviceTable.getRows()) {
			if (b.getId().equals(id)) {
				return b;
			}
		}
		return null;
	}

	@Override
	public List<Service> getAll() {
		ServiceTable serviceTable = deserializeFromXml();
		return serviceTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final ServiceTable serviceTable = deserializeFromXml();
		Service toBeDeletedService = null;
		for (Service b : serviceTable.getRows()) {
			if (b.getId().equals(id)) {
				toBeDeletedService = b;
			}
		}
		serviceTable.getRows().remove(toBeDeletedService);
		serializeToXml(serviceTable);
	}

	@Override
	protected Class<ServiceTable> getTableClass() {
		return ServiceTable.class;
	}

}
